package com.rw.map.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class NavigateCorsConfig {

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		// 允许任何域名访问
		corsConfiguration.addAllowedOrigin("*");
		// 允许任何header访问
		corsConfiguration.addAllowedHeader("*");
		// 允许任何方法访问
		corsConfiguration.addAllowedMethod("*");
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig());
		return new CorsFilter(source);
	}

	@Bean
	public FilterRegistrationBean<NavigateCorsFilter> companyUrlFilterRegister() {
		FilterRegistrationBean<NavigateCorsFilter> registration = new FilterRegistrationBean<NavigateCorsFilter>();
		// 注入过滤器
		registration.setFilter(new NavigateCorsFilter());
		// 拦截规则
		registration.addUrlPatterns("/*");
		// 过滤器名称
		registration.setName("navigateCorsFilter");
		// 过滤器顺序
		registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
		return registration;
	}
}
